package com.dmp.modules.labels;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;

import com.dmp.beans.DmpEntityTags;
import com.dmp.common.Constant;
import com.dmp.db.CarLabelDBConnect;
import com.dmp.factory.ConcreteFactory;
import com.dmp.factory.Factory;
import com.dmp.factory.ILabelRedisDao;
import com.dmp.util.JedisClusterWriteUtils;

/**
 * 
 * @author suzg
 *
 */
public class CarLabelApp {
	private final static String labelCarKey = Constant.LabelRedisKey.LABEL_CAR_KEY;

	public static void main(String[] args) {
		System.out.println("......CarLabelApp is running ......");
		long begin = System.currentTimeMillis();
		List<DmpEntityTags> list = getEntityFromDB();
		long end = System.currentTimeMillis();
		System.out.println("获得了所有标签数据，耗时：" + ((end - begin) / 1000) + "秒");
		if (!CollectionUtils.isEmpty(list)) {
			getRedisDao();
			// 先删除
			JedisClusterWriteUtils.del(labelCarKey);
			System.out.println("删除redis中key：" + labelCarKey + "的数据");
			System.out.println("开始添加新数据到redis中:");
			long start = System.currentTimeMillis();
			// 后新增
			for (DmpEntityTags entity : list) {
				JedisClusterWriteUtils.setHashMap(labelCarKey, entity.getUrl(), entity.getLables());
			}
			end = System.currentTimeMillis();
			System.out.println("redis添加完毕，耗时" + ((end - start) / 1000) + "秒");
		}
		end = System.currentTimeMillis();
		System.out.println("......CarLabelApp is ended ......");
		System.out.println("总耗时：" + ((end - begin) / 1000) + "秒");
	}

	/**
	 * 获得redis操作dao
	 * 
	 * @return
	 */
	private static ILabelRedisDao getRedisDao() {
		Factory factory = new ConcreteFactory();
		String redisPath = "car-label.properties";
		return factory.createLabelRedisDao(redisPath);
	}

	/**
	 * 从数据库中获得所有汽车标签的数据
	 * 
	 * @return
	 */
	private static List<DmpEntityTags> getEntityFromDB() {
		List<DmpEntityTags> result = new ArrayList<DmpEntityTags>();

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			String sql = "select url as 'URL', lables as 'LABLES' from dmp_entity_tags;";

			conn = CarLabelDBConnect.getConnection();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			DmpEntityTags entity = null;
			while (rs.next()) {
				// 实例化一个用户对象
				entity = new DmpEntityTags();
				// 对用户对象属性赋值
				entity.setLables(rs.getString("LABLES"));
				entity.setUrl(rs.getString("URL"));
				result.add(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			CarLabelDBConnect.release(conn, ps, rs);
		}
		return result;
	}

}
